//
//  GMWebViewController.m
//  zbomc
//
//  Created by 雷国敏 on 16/9/28.
//  Copyright © 2016年 N-wei. All rights reserved.
//

#import "GMWebViewController.h"
#import <WebKit/WebKit.h>
#import "GMSystemTool.h"
#import "NWloginViewController.h"



@interface GMWebViewController ()<WKNavigationDelegate,WKUIDelegate, WKScriptMessageHandler>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong) MBProgressHUD *HUD;

@property (nonatomic, strong) UIView *statusBarView;
@end

@interface GMWebViewController(){
    NSString *appServerBaseURLStr;
}
@end
@implementation GMWebViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    // hidden status
    //	if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
    //		[self prefersStatusBarHidden];
    //		[self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    //	}
    
    
    
    
    
    //2 hidden navigation
    self.navigationController.navigationBarHidden = YES;
    
    //3 check network
    [GMSystemTool gm_reachability];
    
    //4 black
    //	self.view.backgroundColor = [[UIColor darkGrayColor]colorWithAlphaComponent:0.5];
    
    //	HUD.contentColor = [UIColor colorWithHexString:@"#10D45F"];
    //	HUD.tintColor = [UIColor colorWithHexString:@"#10D45F"];
    //	HUD.tintColor = [UIColor colorWithHexString:@"#10D45F"];
}

//
//-(BOOL)prefersStatusBarHidden
//{
//	return YES;
//}



-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //1 clearCache
    //	[self clearCache];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    //	[MBProgressHUD showSuccess:@"SSS"];
    //	[MBProgressHUD showError:@"SSS"];
    
    NSString *gm_address = [GMDataHandleTool read:GM_ADDRESS];
    if (gm_address !=nil && gm_address.length > 0) {
        appServerBaseURLStr = [NSString stringWithFormat:@"http://%@:8090/ZbomcSysService/wap/login/login.action",[GMDataHandleTool read:GM_ADDRESS]];
    }else{
        appServerBaseURLStr = AppServerBaseURLString;
    }
    
    self.statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, NEWS_IP_DEVICE_WIDTH, [UIApplication sharedApplication].statusBarFrame.size.height)];
    
    self.view.backgroundColor= [UIColor colorWithHexString:@"#347AEA"];
    //	[UIColor colorWithRed:(57.0f/255.0f ) green:(125.0f/255.0f ) blue:(231.0f/255.0f) alpha:1];
    [self.view addSubview:self.statusBarView];
    [self.view bringSubviewToFront:self.statusBarView];
    
    if(self.isPush){
        [self setupPushWebView];
    }else{
        [self setupWebView];
    }

}


/**
 * setup UI
 */
-(void)setupWebView{
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, NEWS_IP_DEVICE_WIDTH,NEWS_IP_DEVICE_HEIGHT-20)];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    [self.view addSubview:self.webView];
    
    
    
    self.HUD = [MBProgressHUD showMessage:@"加载中..."];
    self.HUD.backgroundColor =  [[UIColor darkGrayColor]colorWithAlphaComponent:0.4];
    NSString *str = [NSString stringWithFormat:@"%@?phone=%@&password=%@",
                     appServerBaseURLStr,[GMDataHandleTool read:GM_USERNAME],[GMDataHandleTool read:GM_PASSWORD]];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    
    [self.view endEditing:YES];
}




/**
 * setup UI
 */
-(void)setupPushWebView{
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, NEWS_IP_DEVICE_WIDTH,NEWS_IP_DEVICE_HEIGHT-20)];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    [self.view addSubview:self.webView];
    
    
    
    self.HUD = [MBProgressHUD showMessage:@"加载中..."];
    self.HUD.backgroundColor =  [[UIColor darkGrayColor]colorWithAlphaComponent:0.4];
//    NSString *str = @"http://zbomc.com:8090/wap/message/index";
//   wap/login/login.action?phone=zbomc&password=zbomc123456&showtype=3
    NSString *str = [NSString stringWithFormat:@"%@?phone=%@&password=%@&showtype=3",
                     appServerBaseURLStr,[GMDataHandleTool read:GM_USERNAME],[GMDataHandleTool read:GM_PASSWORD]];
    
    
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    
    //    [self.view endEditing:YES];
}




#pragma mark ---------------------WKWebView--------------------
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    LxDBAnyVar(webView.URL.absoluteString );
    if ([webView.URL.absoluteString isEqualToString:appServerBaseURLStr]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
//
//
//}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
    //	LxDBAnyVar(webView.URL.absoluteString );
    
    if ([webView.URL.absoluteString isEqualToString:appServerBaseURLStr]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}




-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSString *urlStr = [[navigationAction.request URL] absoluteString];
    [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    urlStr = [urlStr stringByRemovingPercentEncoding];
    
    
    /*
     分享操作实现（和返回操作一样）
     需要返回参数 标题、描述（正文）、图片、网址，采用“__”分隔（两个下划线 英文输入）
     
     ios端是通过拦截WEB端传递的URL 来判断相应的执行，因此
     
     1点击微信分享按钮的时候，需要给iOS端传递一个操作指令
     约定操作指令 action://share__文件标题__文件路径
     例如 "action://share__HIS系统-20170228_汇总_日报__/10000/10000_1_20170228_1_1488214890430.pdf"
     
     2.ios端拦截到该URL,调用JS分享方法
     window.myObj.showpdf("HIS系统-20170228_汇总_日报","/10000/10000_1_20170228_1_1488214890430.pdf");
     */
    
    /*
     1.调用的是 share 方法还是 wwindow.myObj.showpdf 方法？
     */
    //		urlStr = @"action://share__HIS系统-20170228_汇总_日报__/10000/10000_1_20170228_1_1488214890430.pdf";
    
    
    //urlStr = action://share?HIS系统-20170416_汇总_日报&/10000/10000_1_20170416_1_1492275704917.pdf
    if ([urlStr hasPrefix:@"action://share"]) {
        NSArray<NSString *>  *strs = [urlStr componentsSeparatedByString:@"&"];
        
        //share title
        //NSString *title = [NSString stringWithFormat:@"zbmoc %@", [strs[0] componentsSeparatedByString:@"?"][1]]  ;
        NSString *title = [strs[0] componentsSeparatedByString:@"?"][1] ;
        
        //2.分享需要的连接
        NSString *urlStr =[NSString stringWithFormat:@"http://www.zbomc.com/pdf/%@",strs[1]];
        
        //3.调用微信分享
        [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession tilte:title url:urlStr];
        
    }
    
    
    
    decisionHandler(WKNavigationActionPolicyAllow);
}




// 页面开始加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    [self.HUD hideAnimated:YES];
}



- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"userContentController%@%@",userContentController,message);
}



#pragma mark ---------------------Method--------------------
/**
 * clearCache
 */
-(void)clearCache{
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}



- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType tilte:(NSString *)title url:(NSString *)urlStr
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    //NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    //获取app中所有icon名字数组
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSArray *iconsArr = infoDict[@"CFBundleIcons"][@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"];
    NSString *iconLastName = [iconsArr lastObject];
    UIImage *thumImage = [UIImage imageNamed:iconLastName];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:@"zbomc 掌上运营专家" thumImage:thumImage];
    
    //设置网页地址
    shareObject.webpageUrl = urlStr;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        
        NSString *message = nil;
        if (!error){
            message = [NSString stringWithFormat:@"分享成功"];
        }
        else{
            
            
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
            
            message = @"没安装该app";
        }
        
        //			message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
        
        //prompt
        [[[UIAlertView alloc] initWithTitle:@"==分享提示=="
                                    message:message
                           cancelButtonItem:nil
                           otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
        }], nil] show];
        
        /*
         
         if (error) {
         UMSocialLogInfo(@"************Share fail with error %@*********",error);
         }else{
         }
         }*/
        //[self alertWithError:error];
    }];
}




@end
